/*
 * @Author: chengsl
 * @Date: 2022-11-03 14:54:55
 * @LastEditors: chengsl
 * @LastEditTime: 2022-12-01 17:00:33
 * @Description: HTTP服务
 */
var querystring = require('querystring')
var util = require('util')

var http = require('http')
var url = require('url')
var { Logger } = require('./log/logger')
const logger = new Logger({ fileName: 'server.js' })
var { JsonDto } = require('./DTO/JsonDto')
var { getResultStr, errorToString } = require('./utils')

const start = function (route) {
  async function onRequest(request, response) {
    request.setEncoding('utf-8')

    var pathname = url.parse(request.url).pathname
    if (pathname == '/favicon.ico') { // 兼容无效请求
      response.write('无效请求')
      response.end()
      return
    }

    const method = request.method // 请求方式
    let params = url.parse(request.url, true).query // 从URL里面取参数
    const contentType = request.headers['content-type']
    if (method === 'GET') {
      responseFun()
    } else if (method === 'POST') {
      // post 请求需要额外解析 参数信息
      if (contentType === 'application/json') {
        // 定义了一个paramsPost变量，用于暂存请求体的信息
        var paramsPost = ''
        request.on('data', function (chunk) {
          paramsPost += chunk
        })
        request.on('end', function () {
          // post 请求 将URL里面的参数与 requestBody 里的参数合并，若有重复的参数 以requestBody里面的优先
          params = Object.assign(params, JSON.parse(paramsPost))
          responseFun()
        })
      } else if (contentType.indexOf('multipart/form-data') !== -1) {
        let form = new multiparty.Form()
        form.parse(request, function(err, fields, files) {
          // TODO 后面再处理
          // response.end(JSON.stringify({fields: fields, files: files}))
        })
      }
    }

    /**
     * 响应逻辑封装
     */
    async function responseFun() {
      response.writeHead(200, { // 设置响应格式
        'Content-Type': 'application/json;charset=utf-8',
      })
      const JSONDTO = new JsonDto({})
      let result = null
      try {
        result = await route(pathname, params) //这个就是查数据的外包装方法
        if (typeof result === 'string' && result.startsWith('[ERROR]')) {
          // 异常
          JSONDTO.setCode(500).setStatus(500).setMessage(errorToString(result))
        } else {
          // 正常返回
          JSONDTO.setCode(200)
            .setStatus(200)
            .setMessage('请求处理成功')
            .setData(result.result)
          result.optionName &&
            JSONDTO.setMethodType(`${method} - ${result.optionName}`)
        }
      } catch (error) {
        JSONDTO.setCode(500).setStatus(500).setMessage(errorToString(error))
      }
      logger.info(`response响应: ${JSONDTO.toString()}`)
      response.write(JSONDTO.toString())
      response.end()
    }
  }

  http.createServer(onRequest).listen(9527)
  logger.info('服务已启动 ---老程')
  logger.info(`127.0.0.1:${9527}`)
}

module.exports = {
  start,
}
